<script setup lang="ts">
import ChatNav from "./ChatNav.vue";
import ChatDomain from "./ChatDomain.vue";
import ChatContent from "./ChatContent.vue";
import axios from "axios";
import { getUserById, userList } from "../api/user.js";
import io from "socket.io-client";
import store from "../store/index";
import Conversition from "../class/Conversition";
import { ref, reactive, onMounted, getCurrentInstance, provide } from "vue";
import { useMessage } from "naive-ui";
const { proxy, content } = getCurrentInstance() as ComponentInternalInstance;

provide: {
  store;
}

const chatUrl: string = import.meta.env.VITE_BASE_API || "/";
const apiUrl: string = import.meta.env.VITE_BASE_MYAPI || "/";
const message = useMessage();

onMounted(() => {
  init();
});

async function init() {
  if (store.isLogin()) {
    initSocket();
    getUserList();
  } else {
    proxy.$router.replace({
      name: "Home",
    });
  }
}

// 匹配地址栏参数
function GetQueryString(name: string) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
  var r = window.location.search.substr(1).match(reg);
  if (r != null) return unescape(r[2]);
  return null;
}

// 获取用户列表
function getUserList() {
  let query = {
    id: store.state.sender?.Id,
  };
  userList(query).then((res: any) => {
    if (res?.code == 200) {
      store.setPropName("allSessionList", res?.data);
    } else {
      message.error(res?.message);
    }
  });
}

function initSocket() {
  store.setPropName("socket", io(chatUrl));
  store.state.socket.on("connect", () => {
    console.log("连接成功");
    store.state.socket.emit("joinChat", {
      SendId: store.state.sender.Id,
      SendName: store.state.sender.Name,
      ReviceId: -1,
      ReviceName: "",
      NoCode: store.state.noCode,
    });
  });
  store.state.socket.on("disconnect", () => {
    console.log("连接已断开");
  });
  //修改信息状态
  store.state.socket.on("changMsgState", (data: any) => {
    store.state.conversitionList.map((x: Conversition) => {
      if (x.NoCode != null && x.NoCode == data.NoCode) {
        x.State = 1;
      }
    });
  });
  // 加入会话成功
  store.state.socket.on("joinSuccess", (data: any) => {
    store.state.sender.OnlineState = true;
    store.state.conversitionList = data.conversition;

    if (store.state.sessionList.length == 0) {
      store.state.sessionList = data.historySessionList;
    }
  });
  //接收信息
  store.state.socket.on("reviceMsg", (data: Conversition) => {
    if (data.ReciverId == store.state.sender.Id) {
      store.playMusic();
      for (let item of store.state.sessionList) {
        if (
          item.Id == data.SendId &&
          store.state.sessionSelectId == data.SendId
        ) {
          data.ReadFlag = true;
          let query = {
            SendId: data.SendId,
            ReciverId: store.state.sender.Id,
          };
          store.state.socket.emit("changeMsgRead", query);
          break;
        }
      }
    }
    store.sendLocal(data);
    let len =
      store.state.sessionList.filter((x: any) => x.Id == data.SendId)?.length ??
      0;
    if (len === 0) {
      let item = store.state.allSessionList.filter(
        (x: any) => x.Id == data.SendId
      );
      store.state.sessionList.push(...item);
    }
    store.toBottom();
  });
  //多设备在线时，强制旧设备下线
  store.state.socket.on("squeezeOut", (data: any) => {
    if (data.noCode == store.state.noCode) {
      store.logout();
      alert("账户在其他地方登陆，会话已断开");
      proxy.$router.replace({
        name: "Home",
      });
    }
  });
}
</script>

<template>
  <div class="chat">
    <chat-nav />
    <chat-domain />
    <chat-content />
  </div>
</template>

<style scoped lang="less">
.chat {
  width: 100%;
  height: 100%;
  display: flex;
  border-radius: 33px;
}
</style>
